package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jumper.chart.ADFetalHeartChart;
import com.jumper.chart.FHRAndTocoChartLineView;
import com.jumper.chart.detail.FetalRecords;
import com.jumper.data.FHRInfo;
import com.jumper.fetalheart.ADFetalHeart;
import com.jumper.fetalheart.ConnectCallback;
import com.jumper.fetalheart.FinishCallback;
import com.jumper.fetalheart.Mode;
import com.jumper.fetalheart.line.HeadSetUnit;
import com.jumper.help.Mp3RecordTimeCreater;
import com.jumper.help.TimeScheduleCallBack;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.FetalMoveValuesBean;
import com.xn.app.muying.bean.FetalMovementInfo;
import com.xn.app.muying.bean.XinLv;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.DateDialog;

import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 自主监测
 */
public class RecordingActivity extends BaseActivity implements View.OnClickListener {
    private String TAG = this.getClass().getSimpleName();
    private static final String fileFolderPath = Environment.getExternalStorageDirectory()
            + "/ceshi";
    private ArrayList<FetalRecords> fetalRecordsList = new ArrayList<>();
    private TextView tvConnectedState = null;
    private TextView tvTime = null;
    private Button start = null, stop = null, shu = null, qie_huan = null;
    //记录是否开始监测
    boolean isstart = false;
    ADFetalHeartChart mAdFetalHeartChart = null;
    FHRAndTocoChartLineView chartView = null;
    private ADFetalHeart mADFetalHeart = null;
    //一个时间模拟处理类
    private Mp3RecordTimeCreater mp3RecordTimeCreater = null;
    private int moshi = 0;
    RelativeLayout td_0 = null;
    TextView tx_1 = null, tx_2 = null, td_4 = null;
    private int taidong = 0;
    ArrayList<Integer> xinlv = new ArrayList<>();
    //存每次胎动的时间
    private ArrayList<FetalMoveValuesBean> list = new ArrayList<>();
    //数据库
    private DBManager db = null;
    //获取开始时间
    private String shijian = null;
    //判断是否有正常胎心数据
    private int i = 0;
    /**
     * 获取蓝牙适配器
     */
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recording);
        db = new DBManager(this);
        // 得到前面已经初始化的单例。
        // 由于是在前一个界面，初始化，这里就不必要做清理工作。
        mADFetalHeart = ADFetalHeart.getInstance(this);
        // 时间定时器，每0.5秒获取一次数据
        mp3RecordTimeCreater = new Mp3RecordTimeCreater();
        mp3RecordTimeCreater.setTimeScheduleCallBack(new TimeScheduleCallBack() {
            @Override
            public void run() {
                // 判断记录是否已经开始
                // 如果已经开始，就开始更新时间
                if (mADFetalHeart.IsRecording()) {
                    mp3RecordTimeCreater.upDataTimeWithFlag();
                }
                //更新主线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        // 获取胎心设备的数据
                        FHRInfo info = mADFetalHeart.getFHRInfo();
                        if (info == null) return;
                        if (isstart) {
                            tvConnectedState.setText(info.getFhr() + "");
                        } else {
                            tvConnectedState.setText("----");
                        }
                        // 开始记录了，才开始描制胎心曲线
                        if (mADFetalHeart.IsRecording()) {
                            // 胎心
                            int fhr = info.getFhr();
                            //   有些设备是没有宫缩，电量这些信息。。
                            // 宫缩
                            int toco = info.getToco();
                            // 电量
                            int bv = info.getRealDevicePower();
                            // 电量百分比
                            int powerPregress = info.getDevicePower();
//                            chartView.addData(fhr, toco);
                            chartView.addData(fhr);
                            xinlv.add(fhr);
                            if (fhr != 0) {
                                i = fhr;
                            }
                            tvTime.setText(mp3RecordTimeCreater.getTimeString());
                        }
                        Log.d(TAG, "耗时---》" + (System.currentTimeMillis() - startTime));
                    }
                });
            }
        });
        tvConnectedState = (TextView) findViewById(R.id.tx_4);
        td_4 = (TextView) findViewById(R.id.td_4);
        tvTime = (TextView) findViewById(R.id.sc_4);
        // 胎心记录图表
        mAdFetalHeartChart = (ADFetalHeartChart) findViewById(R.id.aDFetalHeartChart);
//        mAdFetalHeartChart.setRatio(2f,2f);
        //这个可以设置比例，胎心视图的  高度/ 宽度
//        mAdFetalHeartChart.setRatio(2f,2f);
        if (mAdFetalHeartChart != null) {
            //设置是否有宫缩 绘图区域
//            mAdFetalHeartChart.setHaveToco(mADFetalHeart.getMode() == Mode.BLUE);
            mAdFetalHeartChart.setHaveToco(false);
            // 得到一个真实的 胎心绘制View
            chartView = mAdFetalHeartChart.getLineView();
            // 设置 一屏显示多少分钟
//            chartView.setOneScreenMinute(5);
            //设置 视图开始滚动时间
//            chartView.setStartScrollTime(1);

            // 设置 滚动间隔，模认一分钟。
            //chartView.setIntervalTime(1);
        }
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        shu = (Button) findViewById(R.id.shu);
        qie_huan = (Button) findViewById(R.id.qie_huan);
        td_0 = (RelativeLayout) findViewById(R.id.td_0);
        tx_1 = (TextView) findViewById(R.id.tx_1);
        tx_2 = (TextView) findViewById(R.id.tx_2);

        // 记录结束的回调
        // 可以在这里进行一些数据库的存储或者网络上传相关
        mADFetalHeart.setFinishCallback(new FinishCallback() {
            @Override
            public void onFinish(String path) {
                Log.d(TAG, "path---->" + path);
            }
        });

        mADFetalHeart.setConnectCallback(new ConnectCallback() {
            @Override
            public void onConnectSuccess() {
            }

            @Override
            public void onConnectFail(boolean setting) {
                int mode = mADFetalHeart.getMode();
                String text = "蓝牙外设";
                if (mode == Mode.LINE) {
                    text = "有线外设";
                }
                //设备断开连接
                Snackbar.make(stop, String.format("%s已断开", text), Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                // 外设断开，这个时候需要停止记录
                if (isstart) {
                    stopClick(1);
                }
            }
        });
        //返回键
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isstart) {
                    stopClick(0);
                } else {
                    finish();
                }
            }
        });
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        qie_huan.setOnClickListener(this);
        shu.setOnClickListener(this);
    }

    protected void startClick() {
        //获取开始监测的时间
        shijian = DateUtils.gettimeDate();
        isstart = true;
        mADFetalHeart.prepare();
        // 准备
        try {
            // 开始工作
            mADFetalHeart.startWork();
            mp3RecordTimeCreater.initTimer();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (moshi == 0) {
            start.setVisibility(View.GONE);
            stop.setVisibility(View.VISIBLE);
            shu.setVisibility(View.VISIBLE);
        } else {
            start.setVisibility(View.GONE);
            stop.setVisibility(View.VISIBLE);
            shu.setVisibility(View.GONE);
        }
        chartView.clean();
        fetalRecordsList.clear();
        // 设置胎心文件存取的图径
        mADFetalHeart.setFile(fileFolderPath, System.currentTimeMillis() + "");
        // 开始 记录胎心
        mADFetalHeart.startRecording();
        mp3RecordTimeCreater.restTimeCount();
    }

    AlertDialog baocun;
    TextView riqi;

    /**
     * 停止监测
     */
    protected void stopClick(int stopint) {
        baocun = MyAlertDialog.SaveDialog(RecordingActivity.this, R.layout.dialog_baocun);
        riqi = (TextView) baocun.findViewById(R.id.ri_qi_xuan_ze);
        riqi.setText(shijian);
        riqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateDialog.showShiJianRiQi(RecordingActivity.this, (TextView) v);
            }
        });
        TextView textView = (TextView) baocun.findViewById(R.id.qu_xiao_bao_cun);
        //继续监测
        if (stopint == 1) {
            mADFetalHeart.stopRecording();
            textView.setText("重新连接");
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    baocun.dismiss();
                    finish();
                }
            });
        } else {
            textView.setText("继续监测");
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    baocun.dismiss();
                }
            });
        }

        //保存并退出
        TextView textview1 = (TextView) baocun.findViewById(R.id.que_ding_bao_cun);
        if (xinlv != null && xinlv.size() > 0 && i != 0) {
            //有数据
            textview1.setText("保存并退出");
            textview1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String shijian1 = riqi.getText().toString();
                    if (!TextUtils.isEmpty(shijian1)) {
                        baocun(shijian);
                        baocun.dismiss();
                    } else {
                        ToastUtil.showToast(RecordingActivity.this, "日期不能为空");
                    }

                }
            });
        } else {
            if (fetalRecordsList != null && fetalRecordsList.size() > 0) {
                textview1.setText("保存并退出");
                textview1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String shijian1 = riqi.getText().toString();
                        if (!TextUtils.isEmpty(shijian1)) {
                            baocun(shijian);
                            baocun.dismiss();
                        } else {
                            ToastUtil.showToast(RecordingActivity.this, "日期不能为空");
                        }

                    }
                });
            } else {
                textview1.setText("退出");
                //没数据
                baocun.findViewById(R.id.que_ding_bao_cun).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        baocun.dismiss();
                        finish();
                    }
                });
            }
        }

    }

    AlertDialog baocundialog;

    void baocun(final String shijian) {
        baocundialog = new MyAlertDialog().ShowDialog(RecordingActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    XinLv xinLv = new XinLv();
                    xinLv.setRecordDate(shijian);
                    xinLv.setFhRs(xinlv);
                    xinLv.setKeepScore(taidong);
                    xinLv.setMode(moshi);
                    xinLv.setRecordSeconds(tvTime.getText().toString());
                    xinLv.setIsUploadToHospital(false);
                    xinLv.setFetalMoveValues(list);
                    xinLv.setFetalMoveTtimes(taidong + "");
                    String p = new Gson().toJson(xinLv);
                    //OkHttp设置post请求编码
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    //OkHttp请求数据
                    Request request = new Request.Builder().url(APIMethod.TianJiaXinLv).
                            addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止工作
        if (isstart) {
            isstart = false;
            mp3RecordTimeCreater.cancelTimer();
            if (mADFetalHeart.IsRecording()) {
                mADFetalHeart.stopWork();
            }
        }
    }

    AlertDialog qiehuan;
    ImageView tai_er, cheng_ren;
    int dianji = 0;
    boolean boo = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //开始监测
            case R.id.start:
                int mode = mADFetalHeart.getMode();
                // 如果本地蓝牙没有开启，则退出
                if (mode == Mode.BLUE) {
                    if (!mBluetoothAdapter.isEnabled()) {
                        ToastUtil.showToast(RecordingActivity.this, "请检查设备连接状态");
                        finish();
                    } else {
                        startClick();
                    }
                }
                //如果当前有线未连接，则退出
                if (mode == Mode.LINE) {
                    if (!HeadSetUnit.checkHeadSet(RecordingActivity.this)) {
                        ToastUtil.showToast(RecordingActivity.this, "请检查设备连接状态");
                        finish();
                    } else {
                        startClick();
                    }
                }
                break;
            //停止监测
            case R.id.stop:
                stopClick(0);
                break;
            //模式切换
            case R.id.qie_huan:
                qiehuan = new MyAlertDialog().ShowDialog(RecordingActivity.this, R.layout.dialog_qie_huan);
                tai_er = (ImageView) qiehuan.findViewById(R.id.tai_er);
                cheng_ren = (ImageView) qiehuan.findViewById(R.id.cheng_ren);
                ImageView qu_xiao = (ImageView) qiehuan.findViewById(R.id.qu_xiao);
                if (moshi == 0) {
                    tai_er.setImageResource(R.mipmap.img_0033);
                    cheng_ren.setImageResource(R.mipmap.img_0036);
                } else {
                    tai_er.setImageResource(R.mipmap.img_0035);
                    cheng_ren.setImageResource(R.mipmap.img_0034);
                }
                tai_er.setOnClickListener(onClickListener);
                cheng_ren.setOnClickListener(onClickListener);
                qu_xiao.setOnClickListener(onClickListener);
                break;
            case R.id.shu:
                String time = mp3RecordTimeCreater.getTimeString();
                String[] my = time.split(":");
                int min = Integer.parseInt(my[0]);
                int sec = Integer.parseInt(my[1]);
                int zong = min * 60 + sec;
                if (dianji == 0 && boo) {
                    boo = false;
                    dianji = zong;
                    taidong++;
                    td_4.setText(taidong + "");
                    fetalRecordsList.add(new FetalMovementInfo(time));
                    //绘制胎动，传入 胎动 的  列表
                    chartView.notify(fetalRecordsList);
                    FetalMoveValuesBean fetalMoveValuesBean = new FetalMoveValuesBean();
                    fetalMoveValuesBean.setTime(time);
                    list.add(fetalMoveValuesBean);
                } else {
                    if (zong - dianji >= 15) {
                        dianji = zong;
                        taidong++;
                        td_4.setText(taidong + "");
                        fetalRecordsList.add(new FetalMovementInfo(time));
                        //绘制胎动，传入 胎动 的  列表
                        chartView.notify(fetalRecordsList);
                        FetalMoveValuesBean fetalMoveValuesBean = new FetalMoveValuesBean();
                        fetalMoveValuesBean.setTime(time);
                        list.add(fetalMoveValuesBean);
                    } else {
                        ToastUtil.showToast(RecordingActivity.this, -(zong - dianji - 15) + "秒后再点击，请稍等！");
                    }
                }
                break;
        }
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //胎儿模式
                case R.id.tai_er:
                    tai_er.setImageResource(R.mipmap.img_0033);
                    cheng_ren.setImageResource(R.mipmap.img_0036);
                    qie_huan.setText("胎儿模式");
                    moshi = 0;
                    td_0.setVisibility(View.VISIBLE);
                    tx_2.setText("正常参考范围 : 110-160");
                    mAdFetalHeartChart.setOverScrollMode(0);
                    qiehuan.dismiss();
                    break;
                //成人模式
                case R.id.cheng_ren:
                    tai_er.setImageResource(R.mipmap.img_0035);
                    cheng_ren.setImageResource(R.mipmap.img_0034);
                    qie_huan.setText("成人模式");
                    moshi = 1;
                    td_0.setVisibility(View.GONE);
//                    tx_1.setText("心率");
                    tx_2.setText("");
                    qiehuan.dismiss();
                    break;
                case R.id.qu_xiao:
                    qiehuan.dismiss();
                    break;
            }
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    baocundialog.dismiss();
                    ToastUtil.showToast(RecordingActivity.this, "保存成功");
                    finish();
                    if (MonitorSelectActivity.monitorSelectActivity != null) {
                        MonitorSelectActivity.monitorSelectActivity.finish();
                    }
                    Intent intent = new Intent(RecordingActivity.this, MonitorSelectActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 1:
                    baocundialog.dismiss();
                    ToastUtil.showToast(RecordingActivity.this, "保存失败");
                    finish();
//                    if (400<=msg.arg1&&msg.arg1<500){
//                        ToastUtil.showToast(RecordingActivity.this, "保存失败");
//                    }else{
//                        Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
//                        HashMap<String, Object> errmsg = new Gson().fromJson(msg.obj.toString(), type);
//                        Type type1 = new TypeToken<HashMap<String, String>>() {}.getType();
//                        HashMap<String, String> error=new Gson().fromJson(errmsg.get("error").toString(),type1);
//                        ToastUtil.showToast(RecordingActivity.this, error.get("message"));
//                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    //物理返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isstart) {
                stopClick(0);
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
